<template>
    <div>
        <el-upload class="inline-block" ref="upload" :accept="accept" :action="uploadUrl" :data="uploadBody"
            :on-remove="handleRemove" :on-change="handleFileChange" :auto-upload="false" :on-exceed="handleExceed"
            :on-success="handleSuccess" :before-upload="beforeAvatarUpload" :file-list="fileList" :on-preview="handlePreview"
            limit="5">
            <el-button style="color:#fff" class="mgt-15" size="small" type="primary">上传<i
                    class="el-icon-upload el-icon--right"></i></el-button>
        </el-upload>
        <div>
            <el-button type="primary" size="small" class="mgt-15" @click="submitUpload" v-if="fileList.length">
                确定上传
            </el-button>
        </div>
        <p class="color-grey fs-14 mgt-10">支持扩展名：{{ accept }}</p>
        <el-image-viewer v-if="showViewer" :on-close="() => {showViewer = false;}" :url-list="srcList" z-index="9999" />
    </div>
</template>

<script>
import { getBusiId } from "@/api/fileMng.js";
import commonUtil from "@/utils/common.js";

export default {
    props: {
        accept: {
            type: String,
            default: '.zip,.doc,.rar,.docx,.pdf,.jpg,.jpeg,.xls,.xlsx,.png'
        },
        busineesType:{
            type: String,
            default:''
        },
        busineesId: {
            type: String,
            default: ''
        },
        fileUploadList:{
            type: Array,
            default: []
        }
    },
    components:{
        "el-image-viewer": () => import("element-ui/packages/image/src/image-viewer"),
    },  
    data(){
       return{
           uploadUrl: commonUtil.getUploadFileUrl(),
           showViewer:false,
           uploadBody: {
               folder: '',
               busineesType: '',
               busineesId: ''
           },
           fileList: [],
           srcList:[],
           uploadFlag:false
       }
    },
    watch:{
        fileUploadList(){
            if (this.fileUploadList.length != 0) {
                let fileList = [];
                this.fileUploadList.forEach(item => {
                    let obj = {
                        name: item.fileName
                    }
                    fileList.push(obj)
                })
                this.fileList = fileList
            } else {
                this.fileList = [];
            }
            console.log(this.fileList);
        },
        busineesId(){
            if (this.busineesId!=''){
                this.uploadBody.busineesId = this.busineesId
            }else{
                this.getBusinessId();
            }
            console.log(this.busineesId)
        }
    },
    mounted() {
        this.getBusinessId();
        this.uploadBody.folder = this.busineesType;
        this.uploadBody.busineesType = this.busineesType;
    },
    activated() {
        
        
    },
    methods: {
        // 过滤重复文件
        filterRepetition(arr) {
            let arr1 = []; //存id
            let newArr = []; //存新数组
            for (let i in arr) {
                if (arr1.indexOf(arr[i].name) == -1) {
                    arr1.push(arr[i].name);
                    newArr.push(arr[i]);
                }
            }
            return newArr;
        },
        handleFileChange(file, fileList) {
            let arr = this.filterRepetition(fileList);
            if (arr.length !== fileList.length) {
                this.$message.error("上传重复文件，已过滤重复文件");
            }
            this.fileList = arr;
            // 上传文件后，自动把文件传给后台，这里做了一个防抖，等待500ms后在传给后台
            // this.debounce(this.submitUpload, 500);
        },
        debounce(fn, waits) {
            if (this.timer) {
                clearTimeout(this.timer);
                this.timer = null;
            }

            this.timer = setTimeout(() => {
                fn.apply(this, arguments); // 把参数传进去
            }, waits);
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        // 确认提交
        submitUpload() {
            if (this.fileList.length === 0) {
                return this.$message.error("请上传文件");
            }
              console.log(this.fileList);
            //限制文件上传大小
            for (var i = 0; i < this.fileList.length;i++){
                console.log(this.fileList[i].size,'size')
                if (this.fileList[i].size !=undefined){
                    let is20M = this.fileList[i].size / 1024 / 1024 < 20;
                    if (!is20M) {
                        return this.$message.error("上传单个文件大小不能超过20MB,请核查!");
                    }
                }
            }
            // console.log(this.fileList);
            this.$refs.upload.submit();
        },
        // 获取businessId
        getBusinessId() {
            getBusiId().then(({ data }) => {
                const { resultBody } = data;
                this.uploadBody.busineesId = resultBody.id;
            });
        },
        // 上传校验
        beforeAvatarUpload(file){
            // console.log(this.fileNameList.findIndex(v=>v==file.name));
            // if (this.fileNameList.findIndex(v=>v==file.name)!=-1){
            //     return this.$message.error('请勿重复提交相同附件')
            // }
            // this.fileNameList.push(file.name)
            // console.log(file.name);
        },
        // 上传文件下载及预览
        handlePreview(file) {
            console.log(file);
            let fileId = '';
            if (file.response && file.response.code == '000000') {
                fileId = file.response.resultBody.fileId;
            }
            if (fileId === '') {
                this.$message.error('暂未上传，不可下载');
                return;
            }
            const type = file.name.substring(file.name.lastIndexOf('.') + 1);
            // 判断文件类型
            if (type === 'jpg' || type === 'png' || type === 'jpeg') {
                let fd = new FormData();
                fd.append('file', file.raw);
                // 存储图片，点击确认按钮时统一上传
                this.showViewer = true;
                this.srcList = [];
                this.srcList.push(URL.createObjectURL(file.raw));
            } else {
                // 在当前浏览器直接下载
                commonUtil.downloadFileCommonTwo(fileId);
            }
        },
        // 图片上传
        handleSuccess(response, file, fileList) {
            if (response.code === '000000') {
                this.$message.success('文件上传成功')
                this.fileList = fileList;
                let params = {
                    fileList: this.fileList,
                    busineesId: this.uploadBody.busineesId
                }
                this.$emit('transferData', params);
            } else {
                this.$message.error('上传失败，请稍后重试');
            }
        },
        handleExceed(files, fileList) {
            this.uploadFlag = true;
            console.log("导入", files, fileList);
            if (fileList.length>5){
                return this.$message.warning(`限制选择5个文件，本次选择了 ${files.length} 个文件`);
            }
        },
    },
}
</script>

<style lang="scss" scoped>

</style>